package com.deep.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.deep.common.model.dto.MemberResponseVO;
import com.deep.common.model.dto.mq.SeckillOrderDTO;
import com.deep.common.utils.OrderSnUtils;
import com.deep.common.utils.R;
import com.deep.seckill.feign.CouponFeignService;
import com.deep.seckill.feign.ProductFeignService;
import com.deep.seckill.interceptor.LoginInterceptor;
import com.deep.seckill.model.constant.SeckillConstant;
import com.deep.seckill.model.dto.SeckillSkuRedisDTO;
import com.deep.seckill.model.vo.SeckillSessionWithSkusVO;
import com.deep.seckill.model.vo.SkuInfoVO;
import com.deep.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 秒杀活动接口实现
 *
 * @author Deep
 * @date 2022/2/21
 */
@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void uploadSeckillSkuLatest3Days() {
        // 1、扫描最近三天的商品需要参加秒杀的活动
        R latest3DaysSession = couponFeignService.getLatest3DaysSession();
        if (latest3DaysSession.getCode() == 0) {
            // 上架商品
            List<SeckillSessionWithSkusVO> seckillSessionWithSkusVOS =
                    latest3DaysSession.getData("data", new TypeReference<List<SeckillSessionWithSkusVO>>() {
                    });
            // 缓存到Redis
            // 1、缓存活动信息
            saveSessionInfos(seckillSessionWithSkusVOS);
            // 2、缓存活动的关联商品信息
            saveSessionSkuInfo(seckillSessionWithSkusVOS);
        }

    }

    //    @SentinelResource(value = "getCurrentSeckillSkusResource",blockHandler = "blockHandler")
    @Override
    public List<SeckillSkuRedisDTO> getCurrentSeckillSkus() {
        // 1、确定当前时间属于哪个秒杀场次
//        long now = new Date().getTime();    // 当前时间（距离1970年）
        long now = System.currentTimeMillis();
        Set<String> keys = redisTemplate.keys(SeckillConstant.SESSION_CACHE_PREFIX + "*");
        for (String key : keys) {
            String replace = key.replace(SeckillConstant.SESSION_CACHE_PREFIX, "");
            long start = Long.parseLong(replace.split("-")[0]);
            long end = Long.parseLong(replace.split("-")[1]);
            if (now >= start && now <= end) {
                // 2、找出该场次对应的所有秒杀商品
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);  // 获取少量集合数据
                BoundHashOperations<String, String, String> operations = redisTemplate.boundHashOps(SeckillConstant.SECKILL_SKU_PREFIX);
                if (range != null) {
                    List<String> jsonStringList = operations.multiGet(range);
                    if (jsonStringList != null && jsonStringList.size() > 0) {
                        return jsonStringList.stream().map(item -> JSON.parseObject((String) item, SeckillSkuRedisDTO.class)).collect(Collectors.toList());
                    }
                } else {
                    throw new IllegalArgumentException("获取商品异常!");
                }
                break;

            }
        }
        return null;
    }

    @Override
    public SeckillSkuRedisDTO getSkuSeckillInfo(Long skuId) {
        Assert.notNull(skuId, "sukId不能为空!");
        // 获取所有key
        BoundHashOperations<String, String, String> operations = redisTemplate.boundHashOps(SeckillConstant.SECKILL_SKU_PREFIX);
        Set<String> keys = operations.keys();
        if (keys != null && keys.size() > 0) {
            // 正则表达式匹配
            String reg = "\\d-" + skuId;
            for (String key : keys) {
                if (Pattern.matches(reg, key)) {
                    String redisValue = operations.get(key);
                    SeckillSkuRedisDTO redisDTO = JSON.parseObject(redisValue, SeckillSkuRedisDTO.class);
                    // 如果当前时间大于等于秒杀活动开始时间并且要小于活动结束时间
                    Long currentTime = System.currentTimeMillis();
                    if (currentTime >= redisDTO.getStartTime() && currentTime <= redisDTO.getEndTime()) {
                        return redisDTO;
                    }
                    redisDTO.setRandomCode(null);
                    return redisDTO;
                }
            }
        }
        return null;
    }

    @Override
    public String seckill(String killId, String key, Integer num) throws InterruptedException {
        Assert.notNull(killId, "killId不能为空!");
        Assert.notNull(key, "key不能为空!");
        Assert.notNull(num, "num不能为空!");

        long now = System.currentTimeMillis();
        // 获取登录用户
        MemberResponseVO loginUser = LoginInterceptor.loginUser.get();
        // 从redis获取秒杀商品详细信息
        BoundHashOperations<String, String, String> operations = redisTemplate.boundHashOps(SeckillConstant.SECKILL_SKU_PREFIX);
        String seckillValueRedis = operations.get(killId);
        if (!StringUtils.hasLength(seckillValueRedis)) {
            return null;
        }
        // (合法性效验)
        SeckillSkuRedisDTO seckillSkuRedisDTO = JSON.parseObject(seckillValueRedis, SeckillSkuRedisDTO.class);
        // ①时间合法性
        if (now >= seckillSkuRedisDTO.getStartTime() && now <= seckillSkuRedisDTO.getEndTime()) {
            // ②效验随机码和商品id
            String randomCode = seckillSkuRedisDTO.getRandomCode();
            String killIdRedis = seckillSkuRedisDTO.getPromotionSessionId() + "-" + seckillSkuRedisDTO.getSkuId();
            if (randomCode.equals(key) && killId.equals(killIdRedis)) {
                // ③验证购物数量是否合理和库存量是否充足
                Integer limit = seckillSkuRedisDTO.getSeckillLimit();   // 限购数量
                int count = Integer.parseInt(Objects.requireNonNull(redisTemplate.opsForValue().get(SeckillConstant.SKU_STOCK_SEMAPHORE + randomCode))); // 限购数量(信号量)
                if (count > 0 && num <= limit && count >= num) {
                    // ④验证这个人是否已经买过了（幂等性处理）,如果秒杀成功，就去占位。userId-sessionId-skuId
                    String userUniqueKey = killIdRedis + loginUser.getId();
                    long ttl = seckillSkuRedisDTO.getEndTime() - now;   // userUniqueKey过期时间
                    Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(userUniqueKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                    if (aBoolean != null && aBoolean) {
                        // 占位成功说明从来没有买过,分布式锁(获取信号量-1)【分布式锁-1】
                        RSemaphore semaphore = redissonClient.getSemaphore(SeckillConstant.SKU_STOCK_SEMAPHORE + randomCode);
                        boolean semaphoreCount = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);     // 扣减信号量(在一百毫秒内扣减信号量，超时则释放信号量)
                        if (semaphoreCount) {
                            // 创建订单号和订单消息发送给MQ
                            // 秒杀成功 快速下单 发送消息到 MQ 整个操作时间在 10ms 左右
                            String orderSn = OrderSnUtils.createOrderSn();
                            SeckillOrderDTO orderDTO = new SeckillOrderDTO();
                            orderDTO.setOrderSn(orderSn);
                            orderDTO.setMemberId(loginUser.getId());
                            orderDTO.setNum(num);
                            orderDTO.setPromotionSessionId(seckillSkuRedisDTO.getPromotionSessionId());
                            orderDTO.setSkuId(seckillSkuRedisDTO.getSkuId());
                            orderDTO.setSeckillPrice(seckillSkuRedisDTO.getSeckillPrice());
                            // TODO 发送给RabbitMQ
                            rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", orderDTO);
                            log.info("耗时..." + (System.currentTimeMillis() - now));
                            return orderSn;
                        }
                    }
                }
            }
        }
        log.info("耗时..." + (System.currentTimeMillis() - now));
        return null;
    }

    /**
     * 缓存活动所有关联的商品信息
     */
    private void saveSessionSkuInfo(List<SeckillSessionWithSkusVO> seckillSessionWithSkusVOS) {
        Assert.notNull(seckillSessionWithSkusVOS, "sessionData不能为空");
        seckillSessionWithSkusVOS.forEach(seckillSessionWithSkusVO -> {
            // 准备hash操作，绑定hash
            BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(SeckillConstant.SECKILL_SKU_PREFIX);
            // 秒杀商品集合
            seckillSessionWithSkusVO.getRelationSkus().forEach(seckillSkuVO -> {
                String token = UUID.randomUUID().toString().replace("-", "");
                // 秒杀场次+商品id作为key
                String redisKey = seckillSkuVO.getPromotionSessionId().toString() + "-" + seckillSkuVO.getSkuId().toString();
                Boolean hasKey = operations.hasKey(redisKey);
                if (hasKey != null && !hasKey) {
                    // 缓存商品信息
                    SeckillSkuRedisDTO seckillSkuRedisDTO = new SeckillSkuRedisDTO();
                    // 1、获取商品详细信息
                    R info = productFeignService.getSkuInfo(seckillSkuVO.getSkuId());   // R.put("skuInfo",skuInfo)
                    if (info.getCode() == 0) {
                        SkuInfoVO skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVO>() {
                        });
                        seckillSkuRedisDTO.setSkuInfo(skuInfo);
                    }
                    // 2、秒杀商品详细信息
                    BeanUtils.copyProperties(seckillSkuVO, seckillSkuRedisDTO);
                    // 3、设置当前商品的秒杀时间信息
                    seckillSkuRedisDTO.setStartTime(seckillSessionWithSkusVO.getStartTime().getTime());
                    seckillSkuRedisDTO.setEndTime(seckillSessionWithSkusVO.getEndTime().getTime());
                    // 4、设置商品的随机码（防止恶意攻击）
                    seckillSkuRedisDTO.setRandomCode(token);

                    // 序列化json格式存入Redis中
                    String key = seckillSkuVO.getPromotionSessionId().toString() + "-" + seckillSkuVO.getSkuId().toString();
                    String value = JSON.toJSONString(seckillSkuRedisDTO);
                    operations.put(key, value);

                    //如果当前这个场次的商品库存信息已经上架就不需要上架
                    // 5、使用库存作为分布式Redisson信号量（限流）
                    // 使用库存作为分布式信号量
                    RSemaphore semaphore = redissonClient.getSemaphore(SeckillConstant.SKU_STOCK_SEMAPHORE + token);
                    // 商品秒杀的库存作为信号量初值
                    semaphore.trySetPermits(seckillSkuVO.getSeckillCount());
                }
            });
        });
    }

    /**
     * 缓存秒杀活动信息
     */
    private void saveSessionInfos(List<SeckillSessionWithSkusVO> seckillSessionWithSkusVOS) {
        Assert.notNull(seckillSessionWithSkusVOS, "sessionData不能为空!");
        for (SeckillSessionWithSkusVO sessionWithSkusVO : seckillSessionWithSkusVOS) {
            // 获取当前活动的开始和结束时间的时间戳
            long startTime = sessionWithSkusVO.getStartTime().getTime();
            long endTime = sessionWithSkusVO.getEndTime().getTime();

            // 存入到Redis中的key
            String key = SeckillConstant.SESSION_CACHE_PREFIX + startTime + "-" + endTime;

            // 判断Redis中是否有该信息，如果没有才进行添加
            Boolean hasKey = redisTemplate.hasKey(key);
            // 缓存活动信息
            if (hasKey != null && !hasKey) {
                // 获取到上架场次中所有商品的 活动场次-商品id
                List<String> skuIds = sessionWithSkusVO.getRelationSkus()
                        .stream().map(item -> item.getPromotionSessionId()
                                + "-" + item.getSkuId().toString()).collect(Collectors.toList());

                redisTemplate.opsForList().leftPushAll(key, skuIds);
            }
        }
    }
}
